package com.systec.smalltools.listener;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.systec.smalltools.entity.ImportInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cmd
 */
public class ExcelListener extends AnalysisEventListener<ImportInfo> {

    public List<ImportInfo> importInfoList = new ArrayList();
    public Map<Integer, String> headLine = new HashMap<>();
    public Map<Integer, String> exceptions = new HashMap<>(16);
    private Logger logger = LoggerFactory.getLogger(ExcelListener.class);

    /**
     * 一行行的读取excel中的内容，跳过表头直接读取第二行
     *
     * @param importInfo
     * @param analysisContext
     */
    @Override
    public void invoke(ImportInfo importInfo, AnalysisContext analysisContext) {
        if (importInfo.getStartTime().after(importInfo.getEndTime())) {
            logger.error("第{}行,解析到一条错误数据：{}，时间先后异常", analysisContext.readRowHolder().getRowIndex() + 1, importInfo.toString());
            exceptions.put(analysisContext.readRowHolder().getRowIndex() + 1, "'时间先后异常': '" + DateUtil.formatDateTime(importInfo.getStartTime()) + "'  '" +
                    DateUtil.formatDateTime(importInfo.getEndTime()) + "'");
        } else {
            logger.info("解析到一条数据：{}", importInfo.toString());
            importInfoList.add(importInfo);
        }
    }

    /**
     * 读取表头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 将表头数据返出去
        headLine = headMap;
    }

    /**
     * 读取后操作
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        logger.error("解析失败，但是继续解析下一行：{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            logger.error("第{}行，第{}列解析异常，数据为：{}", excelDataConvertException.getRowIndex() + 1,
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            //将错误数据存储在一个hashmap里面，在controller中进行返回给前端
            exceptions.put(excelDataConvertException.getRowIndex() + 1, "'数据格式不符合要求'：'" + excelDataConvertException.getCellData() + "'");

        }
    }
}
